package com.gylang.common.jwt;

import com.fasterxml.jackson.core.type.TypeReference;
import com.gylang.common.utils.JsonUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

/**
 * @author gylang,
 * @data 2019/12/7 10:37,
 * @DESC
 */
public class JwtUtils {


    private static final String JWT_PAYLOAD_USER_KEY = "user";
    private static final String JWT_PAYLOAD_AUTHORITIES_KEY = "auth";

    /**
     * 私钥加密token
     *
     * @param userInfo   复合数据
     * @param privateKey 私钥
     * @param expire     过期时间 单位分钟
     * @return JWT
     */
    public static String generateTokenExpireInMinute(Object userInfo, List<String> authorities, PrivateKey privateKey, int expire) {
        System.out.println("过期时间:" + DateTime.now().plusMinutes(expire).toDate());
        return Jwts.builder()
                .claim(JWT_PAYLOAD_AUTHORITIES_KEY, JsonUtils.obj2Str(authorities))
                .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.obj2Str(userInfo))
                .setId(createJTI())
                .setExpiration(DateTime.now().plusMinutes(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }

    public static String generateTokenExpireInMinute(Object userInfo, List<String> authorities,String JTI, PrivateKey privateKey, int expire) {
        System.out.println("过期时间:" + DateTime.now().plusMinutes(expire).toDate());
        return Jwts.builder()
                .claim(JWT_PAYLOAD_AUTHORITIES_KEY, JsonUtils.obj2Str(authorities))
                .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.obj2Str(userInfo))
                .setId(JTI)
                .setExpiration(DateTime.now().plusMinutes(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }
    public static String createJTI() {
        return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
    }

    /**
     * 公钥解析token
     *
     * @param token     用户请求token
     * @param publicKey 公钥
     * @param userType  负载数据类型
     * @param <T>
     * @return 负载数据封装对象
     */
    public static <T> PayLoad<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {

        Jws<Claims> claimsJws = parseToken(token, publicKey);
        System.out.println(JsonUtils.obj2Json("claimsJws" + claimsJws));

        Claims body = claimsJws.getBody();
        PayLoad<T> claims = new PayLoad<T>();
        System.out.println(JsonUtils.obj2Json("claims" + claimsJws));

        claims.setId(body.getId());
        System.out.println("userStr" + JsonUtils.toList(body.get(JWT_PAYLOAD_AUTHORITIES_KEY).toString(), String.class));
        claims.setAuthorities(JsonUtils.toList(body.get(JWT_PAYLOAD_AUTHORITIES_KEY).toString(), String.class));
        claims.setUserInfo(JsonUtils.str2Obj(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
        claims.setExpire(body.getExpiration());
        return claims;
    }

    /**
     * 获取token中的id 过期时间
     *
     * @param token     用户请求令牌
     * @param publicKey 公钥
     * @return 用户新
     */
    public static <T> PayLoad<T> getInfoFromToken(String token, PublicKey publicKey) {
        Jws<Claims> claimsJws = parseToken(token, publicKey);
        Claims body = claimsJws.getBody();
        PayLoad<T> claims = new PayLoad<T>();
        claims.setId(body.getId());
        claims.setExpire(body.getExpiration());
        return claims;
    }


    private static Jws<Claims> parseToken(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }
}
